package fast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * UDPTalker Class
 * 
 * Removes entries from a buffer, establishes where these entries need to be
 * sent and forms a UDP datagram to be sent to a remote host Must be run as a
 * thread.
 * 
 * @version 0.1
 * @author Adam Bell
 * @date 19/01/2010
 */
public class UDPTalker implements Runnable {

	private Buffer talkBuffer;
	private DatagramSocket s;

	/**
	 * Constructor
	 * 
	 * @param b
	 *            The buffer to read from
	 */
	public UDPTalker(Buffer b) {
		talkBuffer = b;
	}

	/**
	 * Thread actions
	 */
	public void run() {

		String[] packet;
		String address;
		int port;
		int id;
		String command;
		String data;

		while (true) {
			s = null;

			try {
				// grab a packet to send from the talk buffer. Split it into
				// s[0] address, s[1] port, s[2] id, s[3] command, s[4] data
				packet = talkBuffer.remove().split("\\|");

				address = packet[0];
				port = Integer.valueOf(packet[1]);
				id = Integer.valueOf(packet[2]);
				command = packet[3];
				data = packet[4];

				// create a new socket
				s = new DatagramSocket();

				// enable broadcast
				s.setBroadcast(true);

				// build string to send
				String out = id + "|" + command + "|" + data;

				// convert to byte array
				byte[] outB = out.getBytes();

				// stuff into a datagram packet & transmit
				DatagramPacket p = new DatagramPacket(outB, outB.length,
						InetAddress.getByName(address), port);
				s.send(p);

			} catch (InterruptedException e) {
				System.out.print(e);
			} catch (UnknownHostException e) {
				System.out.print(e);
			} catch (IOException e) {
				System.out.print(e);
			}// try
		}// while

	}

}
